<template>
    <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible" width="60%">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
                 label-width="80px">
            <el-form-item label="所属分类" prop="cateId">
                <el-input placeholder="请选择分类" :value="current.name" type="text" readonly>
                    <template slot="suffix">
                        <el-button class="el-icon-edit" @click="checkSort" type="text"> 选择分类</el-button>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="题干内容" prop="info">
                <ck-editor ref="ckEditor" :change="contentChanged"/>
            </el-form-item>
            <el-form-item label="选项" prop="choiceqstOps">
                <div>
                    <div v-for="(item, index) in dataForm.choiceqstOps" :key="index"
                         style="display: flex;flex-direction: row;margin-bottom: 20px">
                        <span style="white-space: nowrap;margin-right: 10px">{{item.key}}</span>
                        <div>
                            <div style="display: flex;flex-direction: row;align-content: center;align-items: center">
                                <el-input v-model="item.option" placeholder="选项"/>
                                <i class="el-icon-delete" v-if="dataForm.choiceqstOps.length > 2"
                                   style="margin-left: 10px" @click="removeOption(index)"/>
                            </div>
                        </div>
                    </div>
                    <el-button v-if="dataForm.choiceqstOps.length < 26" type="success" @click="addOption">添加一个选项
                    </el-button>
                </div>
            </el-form-item>
            <el-form-item label="答案" prop="answ">
                <el-radio-group v-model="dataForm.answ">
                    <el-radio-button v-for="(item,index) in dataForm.choiceqstOps" :key="index" :label="item.key"
                                     border/>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="试题难度" prop="level">
                <el-radio-group v-model="dataForm.level">
                    <el-radio-button :label="0">简单</el-radio-button>
                    <el-radio-button :label="1">正常</el-radio-button>
                    <el-radio-button :label="2">困难</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="答案解析" prop="analysis">
                <el-input type="textarea" v-model="dataForm.analysis" placeholder="答案解析"/>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="dataFormSubmit()" :loading="loading">确定</el-button>
        </div>
        <!-- 分类管理 -->
        <el-dialog title="分类管理" :visible.sync="dialogFormVisible" :show-close="false"
                   append-to-body width="30%">
            <paper-cate ref="paperCate" v-if="paperCate" :setCurrent="setCurrent" :current="current"
                        :url="{
                                update:'/exam-admin/ques/cate/update',
                                save:'/exam-admin/ques/cate/save',
                                delete:'/exam-admin/ques/cate/delete',
                                tree:'/exam-admin/ques/cate/tree'
                                }"/>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
            </div>
        </el-dialog>
    </el-dialog>
</template>

<script>
  import paperCate from './../../../views/modules/paper/papercate'
  import CkEditor from '../../../components/ckEditor/ckEditor'

  export default {
    data () {
      let checkOptions = (rule, value, callback) => {
        value.forEach(x => {
          if (!x.option) {
            return callback(new Error(`${x.key}选项不能为空`))
          }
        })
        callback()
      }
      return {
        dialogFormVisible: false,
        current: {},
        paperCate: false,
        visible: false,
        loading: false,
        words: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
        dataForm: {
          id: 0,
          cateId: '',
          info: '',
          questype: 1,
          choiceqstOps: [
            {
              key: 'A',
              option: ''
            },
            {
              key: 'B',
              option: ''
            }
          ],
          answ: '',
          level: 0,
          analysis: ''
        },
        dataRule: {
          cateId: [{required: true, message: '分类不能为空', trigger: 'blur'}],
          info: [{required: true, message: '题干内容不能为空', trigger: 'blur'}],
          choiceqstOps: [{validator: checkOptions, trigger: 'blur'}],
          answ: [{required: true, message: '答案不能为空', trigger: 'blur'}],
          level: [{required: true, message: '试题难度（0-简单，1-普通，2-困难）不能为空', trigger: 'blur'}]
        }
      }
    },
    components: {
      CkEditor,
      paperCate
    },
    methods: {
      contentChanged (content) {
        this.dataForm.info = content
      },
      setCurrent (data) {
        if (data.id) {
          this.current = data
          this.dataForm.cateId = data.id
          this.$nextTick(_ => this.$refs['dataForm'].validateField('cateId'))
        }
      },
      checkSort () {
        this.dialogFormVisible = true
        this.paperCate = true
        this.$nextTick(() => {
          this.$refs.paperCate.init()
        })
      },
      init (id, quesCateId) {
        this.current = {
          name: '',
          id: ''
        }
        this.dataForm.cateId = quesCateId
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/exam-admin/ques/singer/info/${this.dataForm.id}`),
              method: 'post'
            }).then(data => {
              if (data && data.code === 200) {
                this.dataForm.choiceqstOps = []
                this.setCurrent({name: data.data.cateName, id: data.data.cateId})
                this.$refs.ckEditor.setData(data.data.info)
                let options = JSON.parse(data.data.options)
                if (options && options.length > 0) {
                  for (let i = 0; i < options.length; i++) {
                    this.dataForm.choiceqstOps.push({
                      key: options[i].key,
                      option: options[i].option
                    })
                  }
                }
                this.dataForm.answ = data.data.answ
                this.dataForm.info = data.data.info
                this.dataForm.level = data.data.level
                this.dataForm.analysis = data.data.analysis
              }
            })
          } else {
            this.$refs.ckEditor.setData('')
            this.dataForm.choiceqstOps = [
              {
                key: 'A',
                option: ''
              },
              {
                key: 'B',
                option: ''
              }
            ]
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: this.$http.adornUrl(`/exam-admin/ques/singer/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: {
                'id': this.dataForm.id || undefined,
                'cateId': this.dataForm.cateId,
                'info': this.dataForm.info,
                'options': JSON.stringify(this.dataForm.choiceqstOps.filter(x => x.option !== '')),
                'answ': this.dataForm.answ,
                'level': this.dataForm.level,
                'analysis': this.dataForm.analysis,
                'quesType': this.dataForm.questype
              }
            }).then(data => {
              if (data && data.code === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500
                })
                this.visible = false
                this.$emit('refreshDataList')
              } else {
                this.$message.error(data.msg)
              }
              this.loading = false
            })
          }
        })
      },
      addOption () {
        if (this.dataForm.choiceqstOps.length >= 26) {
          return false
        }
        this.dataForm.choiceqstOps.push(
          {
            key: this.words[this.dataForm.choiceqstOps.length],
            option: ''
          }
        )
      },
      // 移除一个选项
      removeOption (index) {
        this.dataForm.choiceqstOps.splice(index, 1)
        for (let i = 0; i < this.dataForm.choiceqstOps.length; i++) {
          this.dataForm.choiceqstOps[i].key = this.words[i]
        }
        this.$nextTick(_ => this.$refs['dataForm'].validateField('choiceqstOps'))
      }
    }
  }
</script>
